﻿using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen;
using SHZY.BaseData.Entitys.Common.Dto.Customer;
using SHZY.BaseData.Entitys.Common.Dto.Factory;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Interfaces.Common;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Logging.Attributes;
using SHZY.Systems.Entitys.Dto.Module;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：工厂建模.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Factorystructure", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBaseFactorystructureService : IComBaseFactorystructureService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseFactorystructureEntity> _repository;

    /// <summary>
    /// 服务基础仓储.-班组
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseFactorystructureEntity> _repository_children;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBaseFactorystructureService"/>类型的新实例.
    /// </summary>
    public ComBaseFactorystructureService(
        ISqlSugarRepository<ComBaseFactorystructureEntity> qmsBaseFactorystructureRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBaseFactorystructureRepository;
        _repository_children = qmsBaseFactorystructureRepository;
        _dataInterfaceService = dataInterfaceService;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取所有工厂信息.
    /// </summary>
    /// <returns></returns>
    [HttpGet("AllFactory")]
    public async Task<dynamic> GetListAllFactory()
    {
        var data = await _repository.AsQueryable().Where(x => x.Type == "Factory" && x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.EnCode).ToListAsync();
        return new { list = data.Adapt<List<ComBaseFactorystructureInfoOutput>>() };
    }

    /// <summary>
    /// 获取所有车间信息.
    /// </summary>
    /// <returns></returns>
    [HttpGet("AllWorkshop")]
    public async Task<dynamic> GetListAllWorkshop()
    {
        var data = await _repository.AsQueryable().Where(x => x.Type == "Workshop" && x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.EnCode).ToListAsync();
        return new { list = data.Adapt<List<ComBaseFactorystructureInfoOutput>>() };
    }

    /// <summary>
    /// 获取工厂建模.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBaseFactorystructureInfoOutput>();
    }

    /// <summary>
    /// 获取工厂建模列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBaseFactorystructureListQueryInput input)
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null).OrderBy(o => o.SortCode).ToListAsync();
        if (!string.IsNullOrEmpty(input.keyword))
            data = data.TreeWhere(t => t.FullName.Contains(input.keyword) || t.EnCode.Contains(input.keyword), t => t.Id, t => t.ParentId);
        var treeList = data.Adapt<List<ComBaseFactorystructureInfoOutput>>();
        return new { list = treeList.ToTree("-1") };
    }

    /// <summary>
    /// 新建工厂建模.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] ComBaseFactorystructureCrInput input)
    {
        if (await _repository.AnyAsync(x => x.EnCode == input.enCode && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBaseFactorystructureEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (isOk < 1)
            throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 更新工厂建模.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] ComBaseFactorystructureUpInput input)
    {
        if (await _repository.AnyAsync(x => x.Id != input.id && x.EnCode == input.enCode && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);

        var entity = input.Adapt<ComBaseFactorystructureEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除工厂建模.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<ComBaseFactorystructureEntity>().SetColumns(it => new ComBaseFactorystructureEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }

    /// <summary>
    /// 获取Site.
    /// </summary>
    /// <returns></returns>
    [HttpGet("GetSiteList/{account}")]
    [AllowAnonymous]
    [IgnoreLog]
    public async Task<dynamic> GetSiteList(string account)
    {
        if (!string.IsNullOrEmpty(account) && account != "0")
        {
            var userInfo = await _repository.Context.Queryable<UserEntity>().Where(x => x.Account == account && x.DeleteMark == null && x.EnabledMark == 1).FirstAsync();
            if (userInfo != null)
            {
                var siteList = await _repository.Context.Queryable<ComBaseUsersiteRelEntity>().Where(x => x.UserId == userInfo.Id && x.DeleteMark == null && x.EnabledMark == 1).Select(x => x.Site).ToListAsync();
                if (siteList.Count > 0)
                {
                    var data = await _repository.AsQueryable().Where(x => x.Type == "Factory" && siteList.Contains(x.EnCode) && x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.SortCode).ToListAsync();
                    return new { list = data.Adapt<List<ComBaseFactorystructureListOutput>>() };
                }
            }
            return new { list = new JArray() };
        }
        else
        {
            var data = await _repository.AsQueryable().Where(x => x.Type == "Factory" && x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.SortCode).ToListAsync();
            return new { list = data.Adapt<List<ComBaseFactorystructureListOutput>>() };
        }
    }

    /// <summary>
    /// 工厂建模信息下拉框（树形）.
    /// </summary>
    /// <returns></returns>
    [HttpGet("Selector/{id}")]
    public async Task<dynamic> GetSelector(string id)
    {
        var q1 = _repository.Context.Queryable<ComBaseFactorystructureEntity>().Where(x => x.DeleteMark == null)//.OrderBy(x => x.SortCode).OrderBy(x => x.CreatorTime, OrderByType.Desc)
            .Select(x => new ComBaseFactorystructureSelectorOutput { id = x.Id, parentId = x.ParentId, enCode = x.EnCode, fullName = x.FullName, sortCode = x.SortCode, type = x.Type });
        var q2 = _repository.Context.Queryable<ComBaseStationEntity>().Where(x => x.DeleteMark == null)//.OrderBy(x => x.SortCode).OrderBy(x => x.CreatorTime, OrderByType.Desc)
            .Select(x => new ComBaseFactorystructureSelectorOutput { id = x.Id, parentId = x.ParentId, enCode = x.EnCode, fullName = x.FullName, sortCode = x.SortCode, type = "Station" });
        var data = await _repository.Context.UnionAll(q1, q2).ToListAsync();

        if (!id.Equals("0"))
            data.RemoveAll(x => x.id == id);

        return new { list = data.ToTree("-1") };
    }
}